//引入axios实例
import axios from "axios";
//引入Element UI组件
import { Message } from 'element-ui';
import Loading from "../components/loading/index"
//引入env.js
import baseURL from "./env";
// 创建axios实例 写入baseURL和超时器
const service = axios.create({
    baseURL: `${baseURL.prod.baseURL}/api/private/v1`,
    timeout: 2000,
});
let loading = null;
//添加请求拦截
service.interceptors.request.use(function (config) {
    loading = Loading.service();
    // console.log('请求拦截:', config);
    if (config.url !== 'login') {
        const token = sessionStorage.getItem('token');
        if (token) {
            config.headers['Authorization'] = token
        }
    }
    return config;
}, function (error) {
    return Promise.reject(error);
});

//添加响应拦截
service.interceptors.response.use(function (response) {
    setTimeout(() => {
        loading.close()
    }, 1000);
    //成功
    console.log(response);
    const res = response.data;
    const resultOk = [200, 201, 204]
    if (resultOk.includes(res.meta.status)) {
        // Message({
        //     message: res.meta.msg,
        //     type: 'success'
        // })
        return res.data;
    }
    Message({
        message: res.meta.msg,
        type: 'error'
    })
    // return Promise.reject('返回数据有误，请检查');
}, function (error) {
    setTimeout(() => {
        loading.close()
    }, 1000);
    return Promise.reject(error);
});

export default service